package cc.linker.steplink.crm.task;

import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.lock.RedisLock;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.dao.CustomerDao;
import cc.linker.steplink.crm.domain.WxUserInfo;
import cc.linker.steplink.crm.domain.WxUserInfoDto;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 更新用户关注状态
 * @Author: wuyue
 * @Date: 2019/9/10 13:07
 * @Version: v1.8.3
 */
@Slf4j
@Component
public class SubscribeTask {
    private static final String SUBSCRIBE_PROHIBIT_USER = "subscribe_prohibit_user";

    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private HttpService httpService;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @RedisLock("SubscribeTask")
    @Scheduled(cron = "40 10 3 * * ?")
    public void go() {
        LocalDateTime localDateTime = LocalDateTime
                .now()
                .withHour(23)
                .withMinute(59)
                .withSecond(59);
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

        List<Map<String, Object>> customers = customerDao.getAllCustomerHavingOpenidAndToken();
        Map<String, Object> map = new HashMap<>();
        map.put("action", "getWeixinUserInfo");
        for (Map<String, Object> customer : customers) {
            String openId = (String) customer.get("openId");
            String token = (String) customer.get("token");
            // 该用户是否被禁止
            Boolean member = redisTemplate.opsForSet().isMember(SUBSCRIBE_PROHIBIT_USER, openId + token);
            if (member) {
                continue;
            }
            map.put("openid", openId);
            map.put("token", token);
            String result;
            try {
                result = httpService.doPost(systemProperties.getWxpushurl(), JSON.toJSONString(map));
            } catch (Exception e) {
                LOGGER.error("矩阵调用异常");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
                continue;
            }
            WxUserInfoDto wxUserInfoDto = JSON.parseObject(result, WxUserInfoDto.class);
            if (wxUserInfoDto != null && "200".equals(wxUserInfoDto.getErrcode())) {
                WxUserInfo data = wxUserInfoDto.getData();
                if (data != null) {
                    Integer subscribe = data.getSubscribe();
                    if (subscribe != null) {
                        customer.put("subscribe", subscribe);
                        customerDao.updateSubscribeByCustomerId(customer);
                    }
                }
            } else {
                // 加入禁止集合，当天不再请求
                redisTemplate.opsForSet().add(SUBSCRIBE_PROHIBIT_USER, openId + token);
            }
            // 休息一下
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 每天过期
        redisTemplate.expireAt(SUBSCRIBE_PROHIBIT_USER, date);
    }
}
